package h0826;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
  * @description 组合总和
  * @author 不知名帅哥
  * @date 2024/8/26 22:01
  * @version 1.0
*/
public class CombinationSum {
    public static void main(String[] args) {
        int[] candidates=new int[]{2,3,6,7};
        System.out.println(combinationSum(candidates, 9));
    }
    public static List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        backtrack(result, new ArrayList<>(), candidates, target, 0);
        return result;
    }

    private static void backtrack(List<List<Integer>> result,List<Integer> tempList, int[] candidates, int remain, int start) {
        if (remain<0){
            return;
        }else if (remain==0){
            result.add(new ArrayList<>(tempList));
        }else {
            for (int i = start; i < candidates.length; i++) {
                tempList.add(candidates[i]);
                backtrack(result, tempList, candidates, remain-candidates[i], i+1);//递归
                tempList.remove(tempList.size()-1); //回溯
            }
        }
    }
}
